package maple.thelittleredbook.recommendation.controller;

import lombok.extern.slf4j.Slf4j;
import maple.thelittleredbook.common.dto.ApiResponse;
import maple.thelittleredbook.common.service.AuthService;
import maple.thelittleredbook.logging.annotation.SystemLog;
import maple.thelittleredbook.recommendation.dto.ContentFeatureStatisticsDTO;
import maple.thelittleredbook.recommendation.dto.ContentFeatureRetryResponseDTO;
import maple.thelittleredbook.recommendation.service.ContentFeatureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 内容特征管理控制器
 * 提供管理员管理内容特征生成任务的接口
 */
@Slf4j
@RestController
@RequestMapping("/api/content-feature/admin")
public class ContentFeatureAdminController {

    private final ContentFeatureService contentFeatureService;
    private final AuthService authService;

    // 注入配置参数用于返回给前端
    @Value("${content-feature.batch-size}")
    private Integer batchSize;

    @Value("${content-feature.max-concurrent}")
    private Integer maxConcurrent;

    @Value("${content-feature.wait-retry-interval}")
    private Long waitRetryInterval;

    @Value("${content-feature.max-no-lock-attempts}")
    private Integer maxNoLockAttempts;

    @Autowired
    public ContentFeatureAdminController(ContentFeatureService contentFeatureService,
                                         AuthService authService) {
        this.contentFeatureService = contentFeatureService;
        this.authService = authService;
    }

    /**
     * 获取内容特征任务统计信息
     */
    @GetMapping("/statistics")
    @SystemLog(operation = "查询内容特征任务统计")
    public ResponseEntity<ApiResponse<ContentFeatureStatisticsDTO>> getTaskStatistics() {

        // 获取当前用户信息
        Long currentUserId = authService.getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        // 权限验证：只有管理员可以查看
        if (!authService.isCurrentUserAdmin()) {
            return ResponseEntity.ok(ApiResponse.fail("权限不足，只有管理员可以查看任务统计"));
        }

        log.info("管理员查询内容特征任务统计，管理员ID: {}", currentUserId);

        // 获取失败任务数量
        Long failedTaskCount = contentFeatureService.getFailedTaskCount();

        // 获取各状态任务统计
        Map<String, Long> taskStatusStatistics = contentFeatureService.getTaskStatusStatistics();

        // 构建响应DTO
        ContentFeatureStatisticsDTO responseDTO = new ContentFeatureStatisticsDTO();
        responseDTO.setFailedTaskCount(failedTaskCount);
        responseDTO.setTaskStatusStatistics(taskStatusStatistics);

        // 设置系统配置信息
        ContentFeatureStatisticsDTO.SystemConfigDTO systemConfig = new ContentFeatureStatisticsDTO.SystemConfigDTO();
        systemConfig.setBatchSize(batchSize);
        systemConfig.setMaxConcurrent(maxConcurrent);
        systemConfig.setWaitRetryInterval(waitRetryInterval);
        systemConfig.setMaxNoLockAttempts(maxNoLockAttempts);
        responseDTO.setSystemConfig(systemConfig);

        log.info("内容特征任务统计查询成功，失败任务数: {}, 统计信息: {}", failedTaskCount, taskStatusStatistics);
        return ResponseEntity.ok(ApiResponse.success("查询成功", responseDTO));
    }

    /**
     * 重试所有失败的任务
     */
    @PostMapping("/retry-failed")
    @SystemLog(operation = "重试失败的内容特征任务")
    public ResponseEntity<ApiResponse<ContentFeatureRetryResponseDTO>> retryFailedTasks() {

        // 获取当前用户信息
        Long currentUserId = authService.getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        // 权限验证：只有管理员可以执行重试操作
        if (!authService.isCurrentUserAdmin()) {
            return ResponseEntity.ok(ApiResponse.fail("权限不足，只有管理员可以执行重试操作"));
        }

        log.info("管理员执行重试失败任务操作，管理员ID: {}", currentUserId);

        // 执行重试操作
        Integer retryCount = contentFeatureService.retryAllFailedTasks();

        // 获取操作后的统计信息
        Map<String, Long> updatedStatistics = contentFeatureService.getTaskStatusStatistics();

        // 构建响应DTO
        ContentFeatureRetryResponseDTO responseDTO = new ContentFeatureRetryResponseDTO();
        responseDTO.setRetryCount(retryCount);
        responseDTO.setUpdatedStatistics(updatedStatistics);

        log.info("重试失败任务操作成功，管理员ID: {}, 重置数量: {}", currentUserId, retryCount);
        return ResponseEntity.ok(ApiResponse.success(String.format("成功重置%d个失败任务为待处理状态", retryCount), responseDTO));
    }

    /**
     * 清理超时的处理中任务
     */
    @PostMapping("/cleanup-timeout")
    @SystemLog(operation = "清理超时的内容特征任务")
    public ResponseEntity<ApiResponse<ContentFeatureRetryResponseDTO>> cleanupTimeoutTasks(
            @RequestParam(value = "timeoutMinutes", required = false) Integer timeoutMinutes) {

        // 获取当前用户信息
        Long currentUserId = authService.getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        // 权限验证：只有管理员可以执行清理操作
        if (!authService.isCurrentUserAdmin()) {
            return ResponseEntity.ok(ApiResponse.fail("权限不足，只有管理员可以执行清理操作"));
        }

        // 默认超时时间30分钟
        if (timeoutMinutes == null || timeoutMinutes <= 0) {
            timeoutMinutes = 30;
        }

        log.info("管理员执行清理超时任务操作，管理员ID: {}, 超时时间: {}分钟", currentUserId, timeoutMinutes);

        // 执行清理操作
        Integer cleanupCount = contentFeatureService.cleanupTimeoutProcessingTasks(timeoutMinutes);

        // 获取操作后的统计信息
        Map<String, Long> updatedStatistics = contentFeatureService.getTaskStatusStatistics();

        // 构建响应DTO
        ContentFeatureRetryResponseDTO responseDTO = new ContentFeatureRetryResponseDTO();
        responseDTO.setRetryCount(cleanupCount);
        responseDTO.setUpdatedStatistics(updatedStatistics);

        log.info("清理超时任务操作成功，管理员ID: {}, 清理数量: {}, 超时时间: {}分钟",
                currentUserId, cleanupCount, timeoutMinutes);
        return ResponseEntity.ok(ApiResponse.success(String.format("成功清理%d个超时任务（超时时间: %d分钟）", cleanupCount, timeoutMinutes), responseDTO));
    }
}